package com.lizk.study.netty.day002;

import com.lizk.study.netty.entity.ClientContent;
import com.lizk.study.netty.utils.NettyUtils;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * @author lizhikui
 * @date 2019/6/16 9:45
 */
public class MyClient {
    public static void main(String[] args) {
        ClientContent clientContent = NettyUtils.createClientContent(NioSocketChannel.class);

        clientContent.getBootstrap().handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0,4,0,4))
                        .addLast(new LengthFieldPrepender(4))
                        .addLast(new StringDecoder(CharsetUtil.UTF_8))
                        .addLast(new StringEncoder(CharsetUtil.UTF_8))
                        .addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ctx.writeAndFlush("client:你好");
                            }

                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                System.out.println(ctx.channel().remoteAddress());
                                System.out.println(msg);
                                ctx.writeAndFlush("client:你不好");
                            }
                        });


            }
        });

        try {
            ChannelFuture channelFuture = NettyUtils.conn(clientContent, "127.0.0.1", 9999);

        } catch (InterruptedException e) {
            NettyUtils.stop(clientContent);
        }

    }
}
